# -*- coding: UTF-8 -*-

# Copyright (c) 2007 Daniele Favara <nomed@dsslive.org>.
#
# This is free software you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# This software is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franilin St, Fifth Floor, Boston, MA

import optparse

OptionValueError = optparse.OptionValueError

class HelpFormatter(optparse.HelpFormatter):

    def __init__(self):
        optparse.HelpFormatter.__init__(self, 2, 24, 79, 1)

    def format_usage(self, usage):
        return "Usage: %s\n" % usage

    def format_heading(self, heading):
        return "\n%*s%s:\n" % (self.current_indent, "", heading.capitalize())
        "options"

    def format_description(self, description):
        return description.strip()

    def format_option(self, option):
        help = option.help
        if help:
            option.help = help.capitalize()
        result = optparse.HelpFormatter.format_option(self, option)
        option.help = help
        return result

class OptionParser(optparse.OptionParser):

    def __init__(self, usage=None, help=None, examples=None,
                 **kwargs):
        if not "formatter" in kwargs:
            kwargs["formatter"] = HelpFormatter()
        optparse.OptionParser.__init__(self, usage, **kwargs)
        self._override_help = help
        self._examples = examples

    def format_help(self, formatter=None):
        if formatter is None:
            formatter = self.formatter
        if self._override_help:
            result = self._override_help.strip()
            result += "\n"
        else:
            result = optparse.OptionParser.format_help(self, formatter)
            result = result.strip()
            result += "\n"
            if self._examples:
                result += formatter.format_heading("examples")
                formatter.indent()
                for line in self._examples.strip().splitlines():
                    result += " "*formatter.current_indent
                    result += line+"\n"
                formatter.dedent()
        result += "\n"
        return result

# vim:et:ts=4:sw=4

